<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="./js/jquery/jquery.js"></script>
<script src="./js/common/common.js"></script>
<script src="./js/common/errorCodeHandler.js"></script>
<style>
    table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
    }
</style>
<body>
<h2>用户信息列表</h2>

<table style="width:40%">
    <thead>
    <tr>
        <th>ID</th>
        <th>用户名</th>
        <th>密码</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>JohnDoe</td>
        <td>password1</td>
    </tr>
    </tbody>
    <!-- 添加更多用户信息行 -->
</table>

<button onclick="showOrHideModal()">新增用户信息</button>

<div id="addUser" style="display:none;">
    <h2>新增用户信息</h2>
    <form id="addUserForm">
        <label for="username">用户名：</label>
        <input type="text" id="username" name="username"><br>
        <label for="password">密码：</label>
        <input type="password" id="password" name="password"><br>
        <input type="submit" value="保存">
    </form>
</div>

<script>

    initTable();

    function showOrHideModal() {
        $("#addUser").toggle();
    }

    function initTable() {
        $('table tbody tr').empty();

        $.ajax({
            type: "GET",
            url: "/study/userInfo/queryUserInfoList",
            success: function (result, status, xhr) {
                if (!errorFilterHandler(result)) {
                    return;
                }
                $.each(result.data, function (index, user) {
                    $('table tr:last').after('<tr><td>' + user.id + '</td><td>' + user.username + '</td><td>' + user.password + '</td></tr>');
                });
            },
            // 失败时触发
            error: function (xhr, status, error) {
                console.log("请求失败触发，status:" + status);
            }
        });
    }

    $("#addUserForm").submit(function (e) {
        e.preventDefault(); // 阻止表单默认提交行为
        var username = $("#username").val();
        var password = $("#password").val();

        var param = {
            username: username,
            password: password
        }

        $.ajax({
            type: "POST",
            url: "/study/userInfo/saveUserInfo",
            data: JSON.stringify(param),
            contentType: "application/json", // 默认为application/x-www-form-urlencoded
            success: function (result, status, xhr) {
                if (!errorFilterHandler(result)) {
                    return;
                }
                showOrHideModal();
                initTable();
            },
            // 失败时触发
            error: function (xhr, status, error) {
                console.log("请求失败触发，status:" + status);
            }
        });
    })
</script>

</body>
</html>